package com.example.demo.core.aspect;

import com.alibaba.fastjson.JSON;
import com.example.demo.core.annotations.RedisSetString;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Objects;

@Aspect
@Component
public class RedisSetStringAspect {
//
//    @Autowired
//    private StringRedisTemplate redisTemplate;
//
//    @Pointcut("@annotation(com.example.demo.core.annotations.RedisSetString)")
//    public void pointcutRedisSetString() {
//    }
//
//    //该注解表示拦截添加了@RedisgetString注解的方法体
//    @Around(value = "pointcutRedisSetString()")
//    public Object redisSetStringBefore(ProceedingJoinPoint joinPoint) throws Throwable {
//        //获取方法
//        MethodSignature sign = (MethodSignature) joinPoint.getSignature();
//        Method method = sign.getMethod();
//        //获取方法上的注解
//        RedisSetString annotation = method.getAnnotation(RedisSetString.class);
//        //获取request
//        HttpServletRequest request = (Objects.requireNonNull((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())).getRequest();
//        //在request中获取请求参数
//        String parameter = request.getParameter(annotation.keys());
//        //将注解中的key和参数拼接成一个字符串
//        String key = annotation.key() + ":" + request.getParameter(annotation.keys());
//        //调用方法，并且获得返回结果
//        Object result = joinPoint.proceed();
//        if (result != null){
//            if (annotation.expire() != 0L) {
//                redisTemplate.opsForValue().set(key, JSON.toJSONString(result));
//            } else {
//                redisTemplate.opsForValue().set(key, JSON.toJSONString(result), annotation.expire(), annotation.timeUnit());
//            }
//        }
//        return result;
//
//    }
}
